package com.jiangjiang.eshop.inventory.updater;

import com.jiangjiang.eshop.common.help.DateHelper;
import com.jiangjiang.eshop.inventory.constant.GoodsStockStatus;
import com.jiangjiang.eshop.inventory.domain.GoodsStockEntity;
import com.jiangjiang.eshop.inventory.service.InventoryGoodsStockService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author Jianghaowen
 * @Date 2021/6/7
 * @Description: TODO
 * @Version V1.0
 **/
@Slf4j
public abstract class AbstractStockUpdater implements StockUpdater {

    protected InventoryGoodsStockService goodsStockService;

    protected List<GoodsStockEntity> goodsStockEntities;

    private DateHelper dateHelper;


    public AbstractStockUpdater(InventoryGoodsStockService goodsStockService,
                                List<GoodsStockEntity> goodsStockEntities,
                                DateHelper dateHelper) {
        this.goodsStockService = goodsStockService;
        this.goodsStockEntities = goodsStockEntities;
        this.dateHelper = dateHelper;
    }


    /**
     * 库存更新总方法
     *
     * @return
     */
    @Override
    public Boolean updateGoodsStock()  {
       try {
           // 更新商品销售库存
           this.updateSaleStockQuantity();
           // 更新商品锁定库存
           this.updateLockStockQuantity();
           // 更新商品已销售库存
           this.updateSoldStockQuantity();
           // 更新库存状态
           this.updateStockStatus();
           // 执行库存更新总方法
          return  this.executeUpdateStock();

       } catch (Exception e){
           log.warn("AbstractStockUpdater updateGoodsStock error",e);
       }
        return false;
    }

    /**
     * 更新商品可销售库存
     *
     * @throws Exception
     */
    protected abstract void updateSaleStockQuantity() throws Exception;

    /**
     * 更新商品锁定库存
     *
     * @throws Exception
     */
    protected abstract void updateLockStockQuantity() throws Exception;

    /**
     * 更新商品已销售库存
     *
     * @throws Exception
     */
    protected abstract void updateSoldStockQuantity() throws Exception;

    /**
     * 更新库存状态
     *
     * @throws Exception
     */
    private void updateStockStatus() throws Exception {
        for (GoodsStockEntity entity : goodsStockEntities) {
            if (entity.getSaledStockQuantity() > 0) {
                entity.setStockStatus(GoodsStockStatus.IN_STOCK);
            } else {
                entity.setStockStatus(GoodsStockStatus.NOT_IN_STOCK);
            }
            entity.setGmtModified(dateHelper.getCurrentDate());
        }
    }


    /**
     * 更新修改时间
     *
     * @throws Exception
     */
    private Boolean executeUpdateStock() {
       return goodsStockService.updateBatchById(goodsStockEntities);
    }

}
